<?php

namespace app\api\controller;

use app\common\Aliyun\demo\SendSms;
use app\common\library\common;
use think\db\exception\DataNotFoundException;
use think\facade\Db;
use think\facade\Log;
use think\Request;


class Payrnotify extends Wap
{

    /**
     * @param Request $request
     * @return void
     */
    public function index(Request $request)
    {
        //续单加时订单回调
        if (request()->isPost()) {
            // 获取微信回调的数据
            $notifiedData = file_get_contents('php://input');

            //XML格式转换
            $xmlObj = simplexml_load_string($notifiedData, 'SimpleXMLElement', LIBXML_NOCDATA);
            $xmlObj = json_decode(json_encode($xmlObj), true);
            $sign_return = $xmlObj['sign'];

            //支付成功
            if ($xmlObj['return_code'] == "SUCCESS" && $xmlObj['result_code'] == "SUCCESS") {
                unset($xmlObj['sign']);
                $wxapp = Db::name('mini_match')->where('id', 1)->find();
                if ($wxapp['app_id'] && $wxapp['wc_hid'] && $wxapp['api_key']) {
                    $key = $wxapp['api_key'];
                }
                $sign = $this->appgetSign($xmlObj, $key);

                if ($sign === $sign_return) {

                    $order = Db::name('customer_renewal_order')->where('order_on', $xmlObj['out_trade_no'])->find();
                    if ($order['pay_type'] > 0) {
                        $this->returnCode(true, 'OK');
                    }
                    $order['update_time'] = time();
                    $order['pay_time'] = time();
                    $order['pay_type'] = 1;
                    $order['status'] = 1;
                    $order['transaction_id'] = $xmlObj['transaction_id'];
                    if (Db::name('customer_renewal_order')->where('order_on', $xmlObj['out_trade_no'])->update($order)) {
                        Log::record('续单回调');
                        $orderInfo = Db::name('customer_order')->where('id', $order['order_renewal_id'])->find();

                        $orderInfo['end_time'] = $order['end_time'];
                        $orderInfo['pay_price'] = $orderInfo['pay_price'] + $order['pay_price'];
                        $orderInfo['jia_price'] = $orderInfo['jia_price'] + $order['pay_price'];
                        $orderInfo['shi'] = $orderInfo['shi'] + $order['shi'];
                        $orderInfo['is_voice_end'] =0;
                        $orderInfo['is_voice'] = 0;

                        Db::name('customer_order')->where('id', $orderInfo['id'])->update($orderInfo);
                        Log::record('续单，原订单时间更新成功');
                        $course = Db::name('customer_course')->where('id', $orderInfo['seat_id'])->find();
                        $door = Db::name('customer_door_list')->where('id', $course['door_id'])->find();

                        if ($door['door_type'] == 2) {
                            $res = self::mqttopenone($door['door_id'], $order['end_time'] - time());
                        }

                        //更新保洁订单
                        $cleaning = Db::name('customer_order_cleaning')->where('order_on', $orderInfo['order_on'])->find();
                        if ($cleaning) {
                            $room = Db::name('mini_room_list')->where('id', $orderInfo['store_id'])->find();
                            $cleaning['add_time'] = $orderInfo['end_time'];
                            $cleaning['end_time'] = $orderInfo['end_time'] + $room['time'] * 60;
                            Db::name('customer_order_cleaning')->where('order_on', $orderInfo['order_on'])->update($cleaning);
                            Log::record('续单，保洁时间更新成功');
                        }

                        if ($order['coupon_id'] > 0) {
                            $status['status'] = 1;
                            Db::name('mini_user_coupon')->where('id', $order['coupon_id'])->update($status);
                        }


                        $this->returnCode(true, 'OK');
                    }

                }
            }
        }
    }





    /**
     * 回调信息
     * @param $returnCode
     * @param $msg
     * @return void
     */
    private
    function returnCode($returnCode = true, $msg = null)
    {
        // 返回状态
        $return = [
            'return_code' => $returnCode ? 'SUCCESS' : 'FAIL',
            'return_msg' => $msg ?: 'OK',
        ];
        // 记录日志

        die($this->toXml($return));
    }

    /**
     * @content 格式化参数格式化成url参数  生成签名sign
     * @param $Obj
     * @param $appwxpay_key
     * @return string
     */
    public
    function appgetSign($Obj, $appwxpay_key)
    {
        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //签名步骤二：在string后加入KEY
        if ($appwxpay_key) {
            $String = $String . "&key=" . $appwxpay_key;
        }
        //签名步骤三：MD5加密
        $String = md5($String);
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        return $result_;
    }


    /**
     * @content 将数组转成uri字符串
     * @param $paraMap
     * @param $urlencode
     * @return false|string
     */
    public
    function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= strtolower($k) . "=" . $v . "&";
        }
        $reqPar;
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    /**
     * 输出xml字符
     * @param $values
     * @return bool|string
     */
    private
    function toXml($values)
    {
        if (!is_array($values)
            || count($values) <= 0
        ) {
            return false;
        }

        $xml = "<xml>";
        foreach ($values as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }
}